package rensoft.gwt.client.view;

import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.event.logical.shared.AttachEvent.Handler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;

import static cs.java.lang.Lang.doLater;
import static cs.java.lang.Lang.is;


public class UI {
	public static void doLaterOnAttached(Widget widget, final int delay, final Runnable runnable) {
		ensureAttached(widget, new Runnable() {
			public void run() {
				doLater(delay, runnable);
			}
		});
	}

	public static void ensureAttached(IsWidget widget, final Runnable runnable) {
		ensureAttached(widget.asWidget(), runnable);
	}

	public static void ensureAttached(Widget widget, final Runnable runnable) {
		if (widget.isAttached()) runnable.run();
		else {
			EnsureAttachedAttachHandler handler = new EnsureAttachedAttachHandler(runnable);
			HandlerRegistration registration = widget.addAttachHandler(handler);
			handler.setRegistration(registration);
		}
	}

	private static class EnsureAttachedAttachHandler implements Handler {
		private final Runnable runnable;
		private HandlerRegistration registration;

		private EnsureAttachedAttachHandler(Runnable runnable) {
			this.runnable = runnable;
		}

		public void onAttachOrDetach(AttachEvent event) {
			if (event.isAttached()) {
				runnable.run();
				if (is(registration)) registration.removeHandler();
			}
		}

		public void setRegistration(HandlerRegistration registration) {
			this.registration = registration;
		}
	}
}
